#include "Script/ScriptMgr.h"
#include "base/core/os/debug.h"
#include "Common/Lib/GlobalScriptFunc.h"
#include "Common/Lib/TimeScriptFunc.h"
#include "Character/Player.h"
#include "PlayerScriptFunc.h"
#include "SkillScriptFunc.h"

#ifdef _MSC_VER
#pragma warning(disable:4100)
#endif

ScriptMgr::ScriptMgr()
    : m_script(),
      m_memoryPool() 
{}

ScriptMgr::~ScriptMgr() 
{}

bool ScriptMgr::Init() 
{
    if (m_script.Init(false, NULL) != 0) 
	{
        LogErrPrint("[logic] script init fail");
        return false;
    }

    if (!_RegistScriptObject()) {
        LogErrPrint("[logic] regist script object fail");
        return false;
    }

    if (!_LoadBootScript()) 
	{
        LogErrPrint("[logic] load boot script fail");
        return false;
    }

    m_script.GarbageCollect(-1);
    return true;
}

bool ScriptMgr::UnInit() 
{
    m_script.UnInit();
    return true;
}

bool ScriptMgr::Update(uint64_t tick) 
{
    m_script.GarbageCollect(1);
    return 0;
}

bool ScriptMgr::ResetScriptState(bool reload) 
{
    m_script.Reset();
    if (reload) 
	{
        _RegistScriptObject();
        _LoadBootScript();
        m_script.GarbageCollect(-1);
    }
    return 0;
}

bool  ScriptMgr::ReloadScriptFile(const char* fileName) 
{
    bool result = false;
    result =  m_script.CallFuncVoid("ReloadFile", fileName);
    return result;
}

bool ScriptMgr::ReLoadScript() 
{
    _LoadBootScript();
    m_script.GarbageCollect(-1);
    return true;
}

LuaScript* ScriptMgr::GetScript() 
{
    return &m_script;
}

bool ScriptMgr::_LoadBootScript() 
{
	m_script.LoadFile("./data/script/root.lua");
	m_script.CallFuncVoid("RootScript");
    return true;
}

bool ScriptMgr::_RegistScriptObject() 
{
    lua_State* state = m_script.GetState();
    MMO_ASSERT(state);

    m_script.SetGlobal<int32_t>("MODULE_LOGICSERVER", 1);
    m_script.SetGlobal<std::string>("SERVER_NAME", "logic");

	Creature::RegistLuaClass(state);
	Player::RegistLuaClass(state);

	RegistGlobalScriptFunc(state);
	RegistTimeScriptFunc(state);
	
	RegistPlayerScriptFunc(state);
	RegistSkillScriptFunc(state);
	RegistGlobalLSScriptFunc(state);

    return true;
}
